<template>
  <a-modal destroyOnClose :title="$t(title)" :visible="visible" :width="520" @cancel="cancelModal(false)" class="AddAcct">
    <template slot="footer">
      <a-button key="back" @click="cancelModal(false)">
        {{$t('common.cancel')}}
      </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="cancelModal(true)">
        {{$t('common.confirm')}}
      </a-button>
    </template>
    <p class="tag">{{$t('candidateApplication.limit_email_acct')}}</p>
    <a-form :form="form">
      <a-row>
        <a-col>
          <a-form-item :label="$t('common.email')" v-bind="formItemLayout">
            <a-input v-decorator="['email',{rules: [{ required: true, message: `${$t('common.pleaseEnter')}${$t('common.email')}` }]}]" :placeholder="$t('common.email')"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
import { mapState } from 'vuex'
import { sendApplicationMail } from '@/api/resume'
export default {
  name: 'sendEmail',
  props: ['visible', 'deliveryId', 'resumeAttachments'],
  data () {
    return {
      form: this.$form.createForm(this),
      loading: false,
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 20 }
      },
      title: 'candidateApplication.send_rsume_email'
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  watch: {
    visible: {
      handler (newValue, oldValue) {
        if (newValue) {
          this.form.setFieldsValue({ email: '' })
        }
      },
      immediate: true
    }
  },
  methods: {
    cancelModal (flag) {
      this.loading = true
      // 提交数据
      if (flag) {
        this.arrangeData()
      } else {
        this.loading = false
        this.$emit('close')
      }
    },
    arrangeData () {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          let params = {
            resumeAttachment: that.resumeAttachments.map(item => {
              return { resumeAttachmentUrl: item.url, fileName: item.fileName || item.name }
            }),
            deliveryId: this.deliveryId,
            email: values.email
          }
          this.sendData(params)
        } else {
          this.loading = false
        }
      })
    },
    async sendData (params) {
      let res = await sendApplicationMail(params)
      if (res.code === 200) {
        this.$message.success(res.message)
        this.$emit('close')
      } else {
        this.$message.error(res.message)
      }
      this.loading = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
</style>
